<?php
/**
 * Create a new Customer
 */

use Fox\Html\TabPanel\Tab;
use Fox\Html\Wrapper;
use Fox\Html\TabPanel;
use Fox\Common\Customer;
use Fox\Html\Screen;

$xview = Xview::instance();
$mode = $xview->val('mode');
if($mode == 'employee') { 
	$title = "Ajout d'un nouvel intervenant";
} elseif($mode == 'entity') { 
	$title = "Ajout d'une nouvelle entit&eacute;";
} else {
	$title = Msg(Customer::BUNDLE_NAME,17);
}
$screen = new Screen("eCustomer","create");
$screen->mainTitle($title);
$tabPanel = new TabPanel("pCustomer");
$wMasterData = new Wrapper("wMasterData");
$blHeader = Xview::instance()->component("customer", "header");
if($mode == 'employee' || $mode == 'entity') {
	
} else {
	$wMasterData->add($blHeader);
}
$blName = Xview::instance()->component("customer", "name");
$wMasterData->add($blName);
$blAddress = Xview::instance()->component("customer", "address");
$wMasterData->add($blAddress);
$tabPanel->add(new Tab("tMasterData",Msg(Fox\Msg::BUNDLE,Fox\Msg::TITLE_MASTER_DATA),$wMasterData));
$blPartners = Xview::instance()->component("customer", "partners");
if($mode == 'employee') {
	
} else {
	$tabPanel->add(new Tab("tPartners",Msg(Customer::BUNDLE_NAME,40),$blPartners));
}


$screen->add($tabPanel);

if($screen->submitted())
{
	$inputs = $screen->get();
	//
	if(!$screen->errors())
	{
		try {
			// Manage Contacts
		// Manage Partners
		// Create Customer
			$object = new Customer();
			if($mode == 'employee') {
				$inputs['type'] = 'pers';
			} elseif($mode == 'entity') {
				$inputs['type'] = 'offi';
			} 
			$object->setFields($inputs);
			if(!empty($inputs["gPartners"])) {
				foreach($inputs["gPartners"] as $key => $partnerData)
				{
					if(empty($partnerData['partnerid']))
					{
						unset($inputs["gPartners"][$key]);
						$blPartners->item("gPartners")->setDatas($inputs["gPartners"]);
						continue;
					}
					if($partnerData['defaultflag'] == 't')
					{
						$partnerData['defaultflag'] = 1;
					}
					elseif($partnerData['defaultflag'] == 'f')
					{
						$partnerData['defaultflag'] = 0;
					}
					$partner = new Customer\Partner();
					if(empty($partnerData['role']))
					{
						$partnerData['role'] = Role::CONTACT_PERSON;
					}
					//$partnerData['customerid'] = $customer->getId();
					$partner->setFields($partnerData);
					if(isset($partners[$partnerData['partnerid']]))
					{
						unset($partners[$partnerData['partnerid']]);
					}
					$object->partner($partner);
				}
			}
			$object->create();
			$id = $object->getId();
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$object->name1));
			Xview::instance()->redirect("?mod=customer&act=update&customerid=$id&mode=$mode");
		}
		catch(Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e->getMessage());
		}
	}
}

echo $screen->Display();